package com.pagepub.farm.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

public abstract class BaseDao<T> {

	protected JdbcTemplate template;
	protected static String TABLE_NAME=null;
	protected static String QUERY_ALL =  "SELECT * FROM "+TABLE_NAME;

	protected static String QUERY_BY_ID=null;

	protected static String QUERY_ALL_COUNT = "SELECT COUNT(*) FROM "+  TABLE_NAME;

	
	protected static String INSERT_SQL = null;

	protected static String DELETE_SQL =null;

	protected static String UPDATE_SQL = null;
	
	protected ParameterizedRowMapper<T> mapper=null;
	
	public BaseDao(){
		initSql();
		initMapper();
	}
	
	public int getMax(String column) throws SQLException {
		String sql = "select MAX("+column+") from " + TABLE_NAME ;
		return template.queryForInt(sql);
	}
	

	public List<T> getAll() throws SQLException {
		return template.query(QUERY_ALL, mapper);
	}
	public T getByID(int id) throws SQLException {
		List<T> list = template.query(QUERY_BY_ID,
				new Object[] { id }, mapper);
		if (list.size() == 0) {
			return null;
		} else
			return list.get(0);
	}
	
	public void add(T bean) throws SQLException{
		SqlParameterSource ps = new BeanPropertySqlParameterSource(bean);
		NamedParameterJdbcTemplate npTemplate = new NamedParameterJdbcTemplate(
				template.getDataSource());
		template.update(INSERT_SQL, bean);
	}
	
	public void insert(T bean) throws SQLException{
		add(bean);
	}
	
	
	public void update(int id) throws SQLException{
		template.update(DELETE_SQL, id);
	}
	
	public abstract void initSql();
	public abstract void initMapper();
}
